<html>
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta content="maximum-scale=1.2,user-scalable=yes" name="viewport">
		<link rel="stylesheet" href="./css/jsoneditor.min.css" type="text/css">
		<script src="./js/jsoneditor.min.js"></script>
		<script type="text/javascript" src="./js/uni-webview-js@1.5.4.js"></script>
		<style>
			html, body {
				margin: 0;
				padding: 0;
				background-color: #fff;
			}
			.jsoneditor {
				width: 100vw;
				height: 100vh;
			}
		</style>
	</head>
	<body>
		<div id="jsoneditor" class="jsoneditor"></div>
	</body>
	<script>
		var editor;
		var undoManager = {
		  index: 0,
		  stack: [],
		  set(value) {
		    this.stack = this.stack.slice(0, this.index + 1);
		    this.stack.push(value);
		    this.index = this.stack.length - 1;
		  },
		  undo() {
		    if (this.index > 0) {
		      this.index--;
		      return this.stack[this.index];
		    }
		    return null;
		  },
		  redo() {
		    if (this.index < this.stack.length - 1) {
		      this.index++;
		      return this.stack[this.index];
		    }
		    return null;
		  }
		};
		window.onload = function () {
			var search = window.location.search.substring(1)
			var arr = search.split('&')
			var query = {}
			for ( let i = 0; i < arr.length; i++ ) {
				const item = arr[i].split('=')
				query[item[0]] = item[1]
			}
			var jsondata = query['jsondata'] ? JSON.parse(decodeURIComponent(query['jsondata'])) : {}
			undoManager.set(decodeURIComponent(query['jsondata']));
			var readonly = query['readonly']
			var container = document.getElementById('jsoneditor');
			editor = new JSONEditor(container, {
			  mode: readonly == 1 ? 'view' : 'code', // 可选 'code'、'form'、'text'、'tree'、'view'
			  theme: 'light',
			  mainMenuBar: false,
			  onChange: function (e) {
				undoManager.set(editor.getText());
				uni.postMessage({ data: { change: editor.getText() } });
			  },
			  onError: function (err) {
			    alert(err.toString());
			  }
			});
			// 设置编辑器的内容
			editor.set(jsondata);
		}
		function set (jsondata) {
			var text = decodeURIComponent(jsondata.replace(/&aposync;/g, "'"))
			undoManager.set(text);
			uni.postMessage({ data: { change: text } });
			editor && editor.set(JSON.parse(text))
		}
		function update (jsondata) {
			// var text = decodeURIComponent(jsondata.replace(/&aposync;/g, "'"))
			// undoManager.set(text);
			var selection = editor && editor.getTextSelection()
			uni.postMessage({ data: { selection: selection } });
		}
		function undoChange() {
		  const value = undoManager.undo();
		  if (value !== null) {
		    editor && editor.set(JSON.parse(value))
			uni.postMessage({ data: { change: value } });
		  }
		}
		function redoChange() {
		  const value = undoManager.redo();
		  if (value !== null) {
		    editor && editor.set(JSON.parse(value))
			uni.postMessage({ data: { change: value } });
		  }
		}
	</script>
</html>